package com.itgy.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itgy.project.common.ErrorCode;
import com.itgy.project.exception.BusinessException;

import com.itgy.project.mapper.UserInterfaceInfoMapper;
import com.itgy.project.model.entity.InterfaceInfo;
import com.itgy.project.model.vo.InterfaceInfoVO;
import com.itgy.project.service.ChartService;
import com.itgy.project.service.InterfaceInfoService;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Service
public class ChartServiceImpl implements ChartService {

    @Resource
    UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    InterfaceInfoService interfaceInfoService;

    @Override
    public List<InterfaceInfoVO> listTopInterfaceInvoke(int limit) {

        List<InterfaceInfoVO> interfaceInfoVOS = userInterfaceInfoMapper.listTopInvokeInterfaceInfo(limit);

        if(interfaceInfoVOS == null || interfaceInfoVOS.size() == 0)
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);


        //根据id查询接口名称
        LinkedHashMap<Long,InterfaceInfoVO> voLinkedHashMap = new LinkedHashMap<Long, InterfaceInfoVO>(interfaceInfoVOS.size());
        for (InterfaceInfoVO interfaceInfoVO : interfaceInfoVOS) {
            voLinkedHashMap.put(interfaceInfoVO.getId(),interfaceInfoVO);
        }
        LambdaQueryWrapper<InterfaceInfo> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.in(InterfaceInfo::getId,voLinkedHashMap.keySet());

        List<InterfaceInfo> interfaceInfos = interfaceInfoService.list(queryWrapper);

        for (InterfaceInfo interfaceInfo : interfaceInfos) {
            voLinkedHashMap.get(interfaceInfo.getId()).setName(interfaceInfo.getName());
        }

        return new ArrayList<>(voLinkedHashMap.values());

    }
}
